<?php

class WS {
    private $http = null;

    public function __construct() {
        //第三和第四个参数,是在https的情况下需要配置的
        //$this->http = new Swoole\WebSocket\Server('0.0.0.0', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
        $this->http = new Swoole\WebSocket\Server('0.0.0.0', 9502);

        $this->http->set([
            //下面的部分也是用来配置https的ssl证书的
            'ssl_cert_file' => "",
            'ssl_key_file' => "",

            'enable_static_handler' => true,
            'document_root' => "./static",
        ]);
        $this->http->on('Open', [$this, "onOpen"]);
        $this->http->on('Message', [$this, "onMessage"]);
        $this->http->on('Close', [$this, "onClose"]);

        //启动服务器
        $this->http->start();
    }

    public function onOpen($ws, $request) {
        $ws->push($request->fd, "hello,welcome\n");
    }

    public function onMessage($ws, $frame) {
        echo "Message: {$frame->data}\n";
        foreach ($ws->connections as $fd) {
            if ($fd == $frame->fd) {
                $ws->push($fd, "我: {$frame -> data}");
            } else {
                $ws->push($fd, "对方：{$frame -> data}");
            }
        }
    }

    public function onClose($ws, $fd) {
        echo "client:{$fd} is closed\n";
    }
}

new WS();


